import time
import sys
import json
import io
# 设置sys.stdout的编码为UTF-8
sys.stdout.reconfigure(encoding='utf-8')
# 创建一个新的输出流，并设置编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 将 当且路径 添加到path中
sys.path.append(r'.')
from DrissionPage import ChromiumPage
from DrissionPage._pages.chromium_tab import ChromiumTab

def load_param_datas_from_file(file_path):
    with open(file_path, "r", encoding='utf-8') as f:
        json_file_datas = json.load(f)  # load的传入参数为字符串类型
        return json_file_datas


def tmall_upload_image():
    json_data = load_param_datas_from_file('tmall_upload_image.data.json')
    port = json_data['port']
    uploadUrl = json_data['uploadUrl']
    uploadImagePaths = json_data['uploadImagePaths']
    imageDirBeans = json_data['imageDirBeans']

    page = ChromiumPage(addr_or_opts='127.0.0.1:' + str(port))
    tab = page.new_tab()  # 新建标签页，获取标签页对象
    tab.get(uploadUrl)
    # 等待页面加载
    # 目录容器
    tab.wait.load_start()
    from tmall import tmall_upload_image_util

    if imageDirBeans:

        for imageDir in imageDirBeans:
            # 显示所有图片
            ALLImagesPath = uploadImagePaths['ALLImagesPath']
            tab.ele('xpath:' + ALLImagesPath).click()
            time.sleep(2)
            # 第一层目录
            topDirName = imageDir['topDirName']
            tmall_upload_image_util.check_and_create_dir(tab, uploadImagePaths, topDirName)
            time.sleep(2)

            # 第二层目录
            secondDirName = imageDir['secondDirName']
            tmall_upload_image_util.check_and_create_dir(tab, uploadImagePaths, secondDirName)
            time.sleep(2)

            # 商品目录
            itemDirName = imageDir['itemDirName']
            tmall_upload_image_util.check_and_create_dir(tab, uploadImagePaths, itemDirName)
            time.sleep(2)

            # 商品子目录
            itemSubDirName = imageDir['itemSubDirName']
            tmall_upload_image_util.check_and_create_dir(tab, uploadImagePaths, itemSubDirName)
            time.sleep(2)

            # 商品文件 (判断是否已经上传)
            itemSubDirPath = imageDir['itemSubDirPath']
            tmall_upload_image_util.upload_dir_images(tab, itemSubDirPath, uploadImagePaths)
            time.sleep(2)

    tab.close()

tmall_upload_image()
